package tech.aistar.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.*;
import tech.aistar.mapper.UserMapper;
import tech.aistar.pojo.Result;
import tech.aistar.pojo.User;
import tech.aistar.service.UserService;
import tech.aistar.utils.EmailApi;
import tech.aistar.utils.JwtUtils;
import tech.aistar.utils.ValidateCodeUtils;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@RestController
@RequestMapping("user")
public class UserController {
	@Autowired
	private UserService userService;
	// 引入redis
	@Autowired
	private RedisTemplate<String, String> redisTemplate;
	@Autowired
	private EmailApi emailApi;
	
	@PostMapping
	public Result login(@RequestBody User user) {
		User u = userService.login(user.getUsername(), user.getPassword());
		if (u == null) {
			return Result.fail("sorry,username or password error!");
		}
		//生成token
		String token = JwtUtils.generateToken(u);
		Map<String, String> userMap = new HashMap<>();
		userMap.put("token", token);
		userMap.put("username", u.getUsername());
		return Result.success(userMap);
	}
	
	@GetMapping("{email}")
	public Result emailGetCode(@PathVariable("email") String email) {
		// 通过email来获取
		User user = userService.emailLogin(email);
		// 如果没有user为空，那么表示没有这个邮件表示的用户
		if (user == null) {
			return Result.fail("sorry,email error!");
		}
		// 如果存在用户，那么生成code存入redis
		// 生成code
		String code = ValidateCodeUtils.getValidateCode(4);
		// 发送验证码
		emailApi.sendHtmlEmail("验证码", code, email);
		// 存入redis，时间为五分钟
		redisTemplate.opsForValue().set(email, code,5, TimeUnit.MINUTES);
		return Result.success(code);
	}
	
	@GetMapping("{email}/{code}")
	public Result emailLogin(@PathVariable("email") String email,@PathVariable("code") String code) {
		// 通过email取出凑得
		System.out.println(email);
		System.out.println(code);
		String redisCode = redisTemplate.opsForValue().get(email);
		System.out.println(redisCode);
		if(redisCode == null) {
			System.out.println("请获取验证码");
			// 如果为空那么没有验证码
			return Result.fail("请获取验证码");
		} else if (!redisCode.equals(code)) {
		// 	如果不相同那么输入错误
			System.out.println("验证码输入错误");
			return Result.fail("验证码输入错误");
		}
		System.out.println("验证码正确");
		// 验证码正确获取用户生成token
		User u = userService.emailLogin(email);
		//生成token
		String token = JwtUtils.generateToken(u);
		Map<String, String> userMap = new HashMap<>();
		userMap.put("token", token);
		userMap.put("username", u.getUsername());
		return Result.success(userMap);
	}
	
	
}
